<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('估值时间')" prop="valuationTime">
            <el-date-picker
              v-model="form.valuationTime"
              clearable
              style="width: 200px"
              type="date"
              value-format="yyyy-MM-dd"
              :picker-options="pickerOptions"
              :placeholder="$t('估值时间')"
              @change="changeInvestmentTime"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('项目名称')" prop="dealId">
            <MainBodySelect
              v-model="form.dealId"
              :disabled="$route.query.id || $route.query.dealId"
              :placeholder="$t('项目名称')"
              :parameters="'deal'"
              :select-bus-type="'equity'"
              @change="changeDealId($event); changeInvestmentTime()"
            />
          </el-form-item>
        </el-col>
        <!--<el-col :span="12">-->
        <!--  <el-form-item :label="$t('投资时间')" prop="investmentTime">-->
        <!--    <el-date-picker-->
        <!--      v-model="form.investmentTime"-->
        <!--      clearable-->
        <!--      disabled-->
        <!--      style="width: 200px"-->
        <!--      type="date"-->
        <!--      value-format="yyyy-MM-dd"-->
        <!--      :placeholder="$t('投资时间')"-->
        <!--    />-->
        <!--  </el-form-item>-->
        <!--</el-col>-->
        <!--<el-col :span="12">-->
        <!--  <el-form-item :label="$t('总投资成本') + $t('金额单位')" prop="totalInvestmentCost">-->
        <!--    <Money v-model="form.totalInvestmentCost" :unit="'w'" disabled :placeholder="$t('总投资成本')" />-->
        <!--  </el-form-item>-->
        <!--</el-col>-->
        <!--<el-col :span="12">-->
        <!--  <el-form-item :label="$t('已回款本金') + $t('金额单位')" prop="principalRepayment">-->
        <!--    <Money v-model="form.principalRepayment" :unit="'w'" disabled :placeholder="$t('已回款本金')" />-->
        <!--  </el-form-item>-->
        <!--</el-col>-->
        <!--<el-col :span="12">-->
        <!--  <el-form-item :label="$t('已回款收益') + $t('金额单位')" prop="collectionIncome">-->
        <!--    <Money v-model="form.collectionIncome" :unit="'w'" disabled :placeholder="$t('已回款收益')" />-->
        <!--  </el-form-item>-->
        <!--</el-col>-->
        <!--<el-col :span="12">-->
        <!--  <el-form-item :label="$t('已回款总额') + $t('金额单位')" prop="receivedAmount">-->
        <!--    <Money v-model="form.receivedAmount" :unit="'w'" disabled :placeholder="$t('已回款总额')" />-->
        <!--  </el-form-item>-->
        <!--</el-col>-->
        <!--<el-col :span="12">-->
        <!--  <el-form-item :label="$t('剩余投资成本') + $t('金额单位')" prop="remainingInvestmentCost">-->
        <!--    <Money v-model="form.remainingInvestmentCost" :unit="'w'" disabled :placeholder="$t('剩余投资成本')" />-->
        <!--  </el-form-item>-->
        <!--</el-col>-->
        <el-col :span="12">
          <el-form-item :label="$t('公司整体估值') + $t('金额单位')" prop="overallProjectCompany">
            <Money v-model="form.overallProjectCompany" :unit="'w'" disabled :placeholder="$t('公司整体估值')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('项目估值') + $t('金额单位')" prop="dealValuation">
            <Money v-model="form.dealValuation" :unit="'w'" disabled :placeholder="$t('项目估值')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('估值方法')" prop="valuationMethods">
            <el-select v-model="form.valuationMethods" disabled :placeholder="$t('估值方法')">
              <el-option
                v-for="dict in dealValuationSettingOption"
                :key="dict.id"
                :label="$t(dict.method)"
                :value="dict.code"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('较上期估值变动')" prop="valuationChanges">
            <el-input-number v-show="false" v-model="form.valuationChanges" disabled class="colorRed" :precision="2" :controls="false" :placeholder="$t('较上期估值变动')" />
            <div class="el-input el-input--medium is-disabled el-input--suffix">
              <div type="text" disabled="disabled" class="el-input__inner">
                <span :style="{ color: (isEmpty(form.valuationChanges) ? '#b7bbc2' : (form.valuationChanges > 0) ? 'red' : 'green') }">
                  {{ isEmpty(form.valuationChanges) ? $t('较上期估值变动') : (form.valuationChanges + '%') }}
                </span>
              </div>
            </div>
          </el-form-item>
        </el-col>
        <!--<el-col :span="12">-->
        <!--  <el-form-item :label="$t('IRR')" prop="irr">-->
        <!--    <Money v-model="form.irr" disabled :placeholder="$t('IRR')" />-->
        <!--  </el-form-item>-->
        <!--</el-col>-->
        <!--<el-col :span="12">-->
        <!--  <el-form-item :label="$t('MOIC')" prop="moic">-->
        <!--    <Money v-model="form.moic" disabled :placeholder="$t('MOIC')" />-->
        <!--  </el-form-item>-->
        <!--</el-col>-->
        <exchangeRateForm ref="exchangeRateForm" :form="form" :currency-list="investCurrencyList" />
      </el-row>
      <!-- 估值方法 -->
      <div class="area-header" style="margin-top: 10px;">
        <span class="area-header-title">{{ $t('估值方法') }}</span>
      </div>
      <el-table tooltip-effect="darkTable" :data="form.dealAnalysisValuationMethodList" border class="nowrapTable formTable">
        <el-table-column :label="$t('使用估值')" align="center" width="80">
          <template slot-scope="scope">
            <el-form-item>
              <el-radio v-model="form.valuationMethods" :label="scope.row.valuationMethods" @input="clickRadio(scope.$index)">
                <span style="display: none;" />
              </el-radio>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('估值方法')" align="center">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('估值方法') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'dealAnalysisValuationMethodList.' + scope.$index + '.valuationMethods'">
              <span>{{ formatMethod(scope.row.valuationMethods) }}</span>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('公司整体估值')" align="center">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('公司整体估值') }}{{ $t('金额单位') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'dealAnalysisValuationMethodList.' + scope.$index + '.overallValuationCompany'">
              <span>{{ moneyFormat(scope.row.overallValuationCompany, 'w') }}</span>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('项目估值')" align="center">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('项目估值') }}{{ $t('金额单位') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'dealAnalysisValuationMethodList.' + scope.$index + '.dealValuation'">
              <span>{{ moneyFormat(scope.row.dealValuation, 'w') }}</span>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('备注')" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-form-item :prop="'dealAnalysisValuationMethodList.' + scope.$index + '.remark'">
              <span>{{ (scope.row.remark) }}</span>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('操作')" align="center" width="140">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="editMethod(scope.row)">{{ $t('修改') }}</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="delMethod(scope.$index, scope.row)">{{ $t('删除') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="tol">
        <el-dropdown trigger="click" placement="top-end">
          <el-button type="primary" size="mini">
            {{ $t('添加') }}<i class="el-icon-arrow-up" />
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item v-for="item in dealValuationSettingOption" :key="item.id" @click.native="addMethod(item.code)">{{ item.method }}</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
      <div class="area-header" style="margin-top: 10px;">
        <span class="area-header-title">{{ $t('出资主体估值') }}</span>
      </div>
      <el-table tooltip-effect="darkTable" :data="form.dealAnalysisValuationInvestorList" border class="nowrapTable formTable">
        <el-table-column :label="$t('主体名称')" align="center" width="200">
          <template slot-scope="scope">
            <el-form-item :prop="'dealAnalysisValuationInvestorList.' + scope.$index + '.investorName'">
              {{ scope.row.investorName }}
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('总投资成本') + $t('金额单位')" align="center">
          <template slot-scope="scope">
            <el-form-item :prop="'dealAnalysisValuationInvestorList.' + scope.$index + '.overallValuationCompany'">
              <span>{{ moneyFormat(scope.row.totalInvestmentCost, 'w') }}</span>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('剩余投资成本') + $t('金额单位')" align="center">
          <template slot-scope="scope">
            <el-form-item :prop="'dealAnalysisValuationInvestorList.' + scope.$index + '.remainingInvestmentCost'">
              <span>{{ moneyFormat(scope.row.remainingInvestmentCost, 'w') }}</span>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('持股比例') + '(%)'" align="center">
          <template slot-scope="scope">
            <el-form-item :prop="'dealAnalysisValuationInvestorList.' + scope.$index + '.latestShareholdingRatio'">
              <span>{{ moneyFormat(scope.row.latestShareholdingRatio) }}</span>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('所占估值') + $t('金额单位')" align="center">
          <template slot-scope="scope">
            <el-form-item :prop="'dealAnalysisValuationInvestorList.' + scope.$index + '.latestValuation'">
              <span>{{ moneyFormat(scope.row.latestValuation, 'w') }}</span>
            </el-form-item>
          </template>
        </el-table-column>
        <exchange-rate-table
          :form="form"
          :label="$t('所占估值') + $t('金额单位')"
          list-name="dealAnalysisValuationInvestorList"
          source-prop-name="latestValuation"
          target-prop-name="latestValuationRateAmount"
        />
      </el-table>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存 取消按钮-->
      <save-btn has-permi="deal:analysisValuation" />
    </div>

    <el-dialog :title="pePbTitle" :visible.sync="methodPePbOpen" :close-on-click-modal="false" :lock-scroll="false" append-to-body custom-class="dialogForm">
      <valuation-method ref="valuationMethod" @pepbAddMethod="pepbAddMethod" />
    </el-dialog>
    <el-dialog :title="$t('成本法')" :visible.sync="methodLawCostsOpen" :close-on-click-modal="false" :lock-scroll="false" append-to-body custom-class="dialogForm">
      <lawCosts ref="lawCosts" @lawCostsAddMethod="lawCostsAddMethod" />
    </el-dialog>
    <el-dialog :title="$t('回购法')" :visible.sync="methodRepurchaseOpen" :close-on-click-modal="false" :lock-scroll="false" append-to-body custom-class="dialogForm">
      <repurchase ref="repurchase" @repurchaseAddMethod="repurchaseAddMethod" />
    </el-dialog>
    <el-dialog :title="$t('最新融资法')" :visible.sync="methodFinancingLawOpen" :close-on-click-modal="false" :lock-scroll="false" append-to-body custom-class="dialogForm">
      <financingLaw ref="financingLaw" @financingLawAddMethod="financingLawAddMethod" />
    </el-dialog>
  </div>
</template>

<script>
import MainBodySelect from '@/components/MainBodySelect'
import valuationMethod from './method/pepb.vue'
import lawCosts from './method/lawCosts.vue'
import repurchase from './method/repurchase.vue'
import financingLaw from './method/financingLaw.vue'
import exchangeRateForm from '@/components/ExchangeRate/form.vue'
import exchangeRateTable from '@/components/ExchangeRate/table.vue'
import {
  saveDealAnalysisValuation,
  getDealAnalysisValuation,
  deleteAnalysisValuationMethod,
  getDealAnalysisValuationLoadData,
  getValuationLastTimeByTime,
  saveMethodFinancingCache
} from '@/api/deal/analysisValuation/dealAnalysisValuation'
import { listDealValuationSetting } from '@/api/deal/analysisValuation/dealValuationSetting'
import { ruoyiFloat } from '@/utils/ruoyi'
import { findByDealIdToValuation } from '@/api/deal/investment/dealInvestment'
import { getDealBase } from '@/api/base/deal/dealBase'
import { saveDealAnalysisValuationReport } from '@/api/deal/analysisValuation/dealAnalysisValuationReport'
export default {
  components: {
    MainBodySelect,
    valuationMethod,
    lawCosts,
    repurchase,
    exchangeRateForm,
    exchangeRateTable,
    financingLaw
  },
  data() {
    return {
      // 表单参数
      form: {},
      // 遮罩层
      loading: false,
      // 表单校验
      rules: {
        valuationTime: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }],
        dealId: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }],
        valuationMethods: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }]
      },
      pePbTitle: '',
      methodPePbOpen: false,
      methodLawCostsOpen: false,
      methodRepurchaseOpen: false,
      methodFinancingLawOpen: false,
      // pe
      backPeData: undefined,
      // pb
      backPbData: undefined,
      // 成本法
      backLawCostsData: undefined,
      // 回购法
      backRepurchaseData: undefined,
      // 最新融资法
      backFinancingLawData: undefined,
      dealValuationSettingOption: [],
      investCurrencyList: [],
      pickerOptions: {
        shortcuts: [
          { text: ((new Date().getFullYear() - 1) + this.$t('年') + this.$t('一季度')), onClick(picker) { picker.$emit('pick', new Date(new Date((new Date().getFullYear() - 1) + '-03-31'))) } },
          { text: ((new Date().getFullYear() - 1) + this.$t('年') + this.$t('二季度')), onClick(picker) { picker.$emit('pick', new Date(new Date((new Date().getFullYear() - 1) + '-06-30'))) } },
          { text: ((new Date().getFullYear() - 1) + this.$t('年') + this.$t('三季度')), onClick(picker) { picker.$emit('pick', new Date(new Date((new Date().getFullYear() - 1) + '-09-30'))) } },
          { text: ((new Date().getFullYear() - 1) + this.$t('年') + this.$t('四季度')), onClick(picker) { picker.$emit('pick', new Date(new Date((new Date().getFullYear() - 1) + '-12-31'))) } },
          { text: (new Date().getFullYear() + this.$t('年') + this.$t('一季度')), onClick(picker) { picker.$emit('pick', new Date(new Date(new Date().getFullYear() + '-03-31'))) } },
          { text: (new Date().getFullYear() + this.$t('年') + this.$t('二季度')), onClick(picker) { picker.$emit('pick', new Date(new Date(new Date().getFullYear() + '-06-30'))) } },
          { text: (new Date().getFullYear() + this.$t('年') + this.$t('三季度')), onClick(picker) { picker.$emit('pick', new Date(new Date(new Date().getFullYear() + '-09-30'))) } },
          { text: (new Date().getFullYear() + this.$t('年') + this.$t('四季度')), onClick(picker) { picker.$emit('pick', new Date(new Date(new Date().getFullYear() + '-12-31'))) } }
        ]
      }
    }
  },
  created() {
  },
  methods: {
    // 初始化数据
    init(data) {
      this.loading = true
      this.backPeData = undefined
      this.backPbData = undefined
      this.backLawCostsData = undefined
      this.backRepurchaseData = undefined
      this.backFinancingLawData = undefined
      if (data != null && data.id !== undefined) {
        getDealAnalysisValuation(data.id).then(response => {
          this.form = response.data
          this.initData()
          this.loading = false
        }).catch(() => {
          this.loading = false
        })
      } else {
        this.reset()
        this.loading = false
      }

      // 重新加载字典 获取估值方法数据
      listDealValuationSetting({ status: 'enable' }).then(response => {
        this.dealValuationSettingOption = response.rows
      })
    },
    initData() {
      this.form.dealAnalysisValuationMethodList && this.form.dealAnalysisValuationMethodList.forEach(item => {
        if (item.valuationMethods === 'pe') {
          this.backPeData = item.formData
        } else if (item.valuationMethods === 'pb') {
          this.backPbData = item.formData
        } else if (item.valuationMethods === 'hgf') {
          this.backRepurchaseData = item.formData
        } else if (item.valuationMethods === 'zxrz') {
          this.backFinancingLawData = item.formData
        } else if (item.valuationMethods === 'cbf') {
          this.backLawCostsData = item.formData
        }
      })
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        dealId: this.$route.query.id,
        sourceId: undefined,
        valuationTime: undefined,
        investmentTime: undefined,
        totalInvestmentCost: undefined,
        receivedAmount: undefined,
        remainingInvestmentCost: undefined,
        overallProjectCompany: undefined,
        dealValuation: undefined,
        valuationMethods: undefined,
        valuationChanges: undefined,
        currency: 'CNY',
        irr: undefined,
        moic: undefined,
        latest: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        dealAnalysisValuationMethodList: []
      }
      this.resetForm('form')
    },
    /** 取消按钮 */
    cancel() {
      this.$parent.$parent.formOpen = false
      this.$parent.$parent.reset()
    },
    /** 关闭form页面 */
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      if (this.$parent.$parent.formOpen !== undefined) {
        this.$parent.$parent.formOpen = false
      }
      // 刷新list页面
      if (this.$parent.$parent.getList !== undefined) {
        this.$parent.$parent.getList()
      }
    },
    /** 翻译字典 */
    formatMethod(val) {
      var actions = []
      if (this.dealValuationSettingOption) {
        Object.keys(this.dealValuationSettingOption).map((key) => {
          if (this.dealValuationSettingOption[key].code === ('' + val)) {
            actions.push(this.$t(this.dealValuationSettingOption[key].method))
            return false
          }
        })
      }
      return actions.join('')
    },
    /** 根据项目获取对应的值 **/
    changeDealId(dealId) {
      if (dealId) {
        getDealAnalysisValuationLoadData(dealId).then(response => {
          if (response.data === null) {
            response.data = {}
          }
          this.form.investmentTime = response.data.investmentTime
          this.form.principalRepayment = response.data.principalRepayment
          this.form.collectionIncome = response.data.collectionIncome
          this.form.receivedAmount = response.data.receivedAmount
          this.form.totalInvestmentCost = response.data.totalInvestmentCost
          this.form.remainingInvestmentCost = response.data.remainingInvestmentCost
          // 获取项目币种
          getDealBase(this.form.dealId).then(response2 => {
            this.form.currency = this.isEmpty(response2.data.currency) ? 'CNY' : response2.data.currency
          })
        })
      }
    },
    /** 改变估值时间 **/
    changeInvestmentTime() {
      if (!this.isEmpty(this.form.dealId) && !this.isEmpty(this.form.valuationTime)) {
        this.loading = true
        this.investCurrencyList = []
        findByDealIdToValuation(this.form.dealId, this.parseTime(this.form.valuationTime)).then(response => {
          this.form.dealAnalysisValuationInvestorList = []
          response.data && response.data.forEach(item => {
            console.log(item)
            this.form.dealAnalysisValuationInvestorList.push({
              investorId: item.investorId,
              investorType: item.investorType,
              investorName: item.investorName,
              currency: item.currency,
              totalInvestmentCost: item.amountInvestmentFact,
              remainingInvestmentCost: item.remainingInvestmentCost,
              latestShareholdingRatio: item.latestShareholdingRatio
            })
            // 汇率主体
            if (item.currency) {
              this.investCurrencyList.push(item.currency)
            }
          })
          console.log('自动计算主体中的所占估值')
          if (!this.isEmpty(this.form.overallProjectCompany)) {
            this.form.dealAnalysisValuationInvestorList && this.form.dealAnalysisValuationInvestorList.forEach((item, ind) => {
              this.$set(this.form.dealAnalysisValuationInvestorList[ind], 'latestValuation', this.formatNum((item.latestShareholdingRatio / 100) * this.form.overallProjectCompany))
            })
          }
          this.loading = false
        })
      }
    },
    /** 添加估值方法 */
    addMethod(command) {
      // 判断是否存在
      var isExist = true
      this.form.dealAnalysisValuationMethodList && this.form.dealAnalysisValuationMethodList.some(item => {
        if (item.valuationMethods === command) {
          this.$message.error(this.$t('已存在该估值方法, 不能重复添加!'))
          isExist = false
          return true
        }
      })
      if (isExist) {
        if (this.isEmpty(this.form.dealId) || this.isEmpty(this.form.valuationTime)) {
          this.msgError(this.$t('请先选择估值时间或项目!'))
          isExist = false
        }
      }
      if (isExist) {
        this.methodOpen(command, 'add')
      }
    },
    /** 根据类型打开对应的方法页面 **/
    methodOpen(valuationMethods, type) {
      switch (valuationMethods) {
        case 'pe':
        case 'pb':
          this.pePbTitle = valuationMethods === 'pe' ? 'PE' : 'PB'
          this.methodPePbOpen = true
          this.$nextTick(() => {
            if (type === 'edit' && (this.backPeData !== undefined || this.backPbData !== undefined)) {
              this.$refs.valuationMethod.edit({ type: valuationMethods, data: valuationMethods === 'pe' ? this.backPeData : this.backPbData })
            } else {
              this.$refs.valuationMethod.init({ type: valuationMethods, dealId: this.form.dealId, time: this.parseTime(this.form.valuationTime) })
            }
          })
          break
        case 'cbf':
          this.methodLawCostsOpen = true
          this.$nextTick(() => {
            if (type === 'edit' && this.backLawCostsData !== undefined) {
              this.$refs.lawCosts.edit(this.backLawCostsData)
            } else {
              this.$refs.lawCosts.init({ dealId: this.form.dealId })
            }
          })
          break
        case 'hgf':
          this.methodRepurchaseOpen = true
          this.$nextTick(() => {
            if (type === 'edit' && this.backRepurchaseData !== undefined) {
              this.$refs.repurchase.edit(this.backRepurchaseData)
            } else {
              this.$refs.repurchase.init({ dealId: this.form.dealId })
            }
          })
          break
        case 'zxrz':
          this.methodFinancingLawOpen = true
          this.$nextTick(() => {
            if (type === 'edit' && this.backFinancingLawData !== undefined) {
              this.$refs.financingLaw.edit(this.backFinancingLawData)
            } else {
              this.$refs.financingLaw.init({ dealId: this.form.dealId })
            }
          })
          break
        default:
          this.msgError('不存在的类型, 请联系管理员!')
      }
    },
    /** PEPB方法确定回调 **/
    pepbAddMethod(code, data) {
      if (code === 'pe') {
        this.backPeData = JSON.parse(JSON.stringify(data))
      } else {
        this.backPbData = JSON.parse(JSON.stringify(data))
      }
      // 将方法页面中的两个值赋值
      data.overallValuationCompany = data.finalCompanyValuation || 0
      data.dealValuation = data.finalProjectValuation || 0
      // 项目估值
      this.insertMethodData(code, data)
      this.clickRadioByCode(code)
    },
    /** 成本法方法回调 **/
    lawCostsAddMethod(data) {
      this.backLawCostsData = JSON.parse(JSON.stringify(data))
      this.insertMethodData('cbf', data)
      this.clickRadioByCode('cbf')
    },
    /** 回购法确定方法回调 **/
    repurchaseAddMethod(data) {
      this.backRepurchaseData = JSON.parse(JSON.stringify(data))
      this.insertMethodData('hgf', data)
      this.clickRadioByCode('hgf')
    },
    /** 最新融资法确定回调 **/
    financingLawAddMethod(data) {
      data.overallValuationCompany = data.afterValuation
      this.backFinancingLawData = JSON.parse(JSON.stringify(data))
      this.insertMethodData('zxrz', data)
      this.clickRadioByCode('zxrz')
    },
    /** 估值方法数据添加后数据显示到页面 */
    insertMethodData(code, data) {
      if (!(this.form.dealAnalysisValuationMethodList instanceof Array)) {
        this.$set(this.form, 'dealAnalysisValuationMethodList', [])
      }
      this.$nextTick(() => {
        // 确保每种估值方法唯一. 不存在新增, 存在修改
        var isExist = false
        var rowIndex = -1
        this.form.dealAnalysisValuationMethodList && this.form.dealAnalysisValuationMethodList.forEach((item, index) => {
          if (item.valuationMethods === code) {
            isExist = true
            rowIndex = index
          }
        })
        if (isExist) {
          // 修改
          this.form.dealAnalysisValuationMethodList[rowIndex].valuationMethods = code
          this.form.dealAnalysisValuationMethodList[rowIndex].overallValuationCompany = data.overallValuationCompany
          this.form.dealAnalysisValuationMethodList[rowIndex].dealValuation = data.dealValuation
          this.form.dealAnalysisValuationMethodList[rowIndex].remark = data.remark
          this.form.dealAnalysisValuationMethodList[rowIndex].formData = JSON.parse(JSON.stringify(data))
        } else {
          // 新增
          const row = {
            id: undefined,
            valuationId: undefined,
            valuationMethods: code,
            overallValuationCompany: data.overallValuationCompany,
            dealValuation: data.dealValuation,
            remark: data.remark,
            formData: JSON.parse(JSON.stringify(data))
          }
          this.form.dealAnalysisValuationMethodList.push(row)
        }
      })
    },
    /** 选中某个估值方式. 然后进行数据计算回显到主表字段中 - 根据code选中 **/
    clickRadioByCode(code) {
      // 选中新增的这一行
      this.$nextTick(() => {
        this.form.valuationMethods = code
        this.form.dealAnalysisValuationMethodList.forEach((item, index) => {
          if (item.valuationMethods === code) {
            this.clickRadio(index)
          }
        })
      })
    },
    /** 选中某个估值方式. 然后进行数据计算回显到主表字段中 **/
    clickRadio(index) {
      // 公司整体估值
      this.form.overallProjectCompany = this.form.dealAnalysisValuationMethodList[index].overallValuationCompany
      // 项目估值
      this.form.dealValuation = this.form.dealAnalysisValuationMethodList[index].dealValuation
      // 较上期估值变动
      getValuationLastTimeByTime(this.form.dealId, this.parseTime(this.form.valuationTime)).then(response => {
        if (response.data === null) {
          this.form.valuationChanges = 100
        } else {
          // 涨幅跌幅计算方式: (本次估值 - 上次估值) / 上次估值 * 100%
          if (response.data.overallProjectCompany === 0) {
            this.form.valuationChanges = 100
          } else if (this.form.overallProjectCompany === 0) {
            this.form.valuationChanges = -100
          } else {
            var ratio = (this.form.overallProjectCompany - response.data.overallProjectCompany) / response.data.overallProjectCompany * 100
            this.form.valuationChanges = this.formatNum(ratio.toFixed(2))
          }
        }
      })
      // MOIC (已回款总额 + 项目估值）/ 总投资成本
      this.form.moic = this.formatNum((this.formatNum(this.form.receivedAmount) + this.formatNum(this.form.dealValuation)) / this.formatNum(this.form.totalInvestmentCost))
      console.log('自动计算主体中的所占估值')
      this.form.dealAnalysisValuationInvestorList && this.form.dealAnalysisValuationInvestorList.forEach((item, ind) => {
        this.$set(this.form.dealAnalysisValuationInvestorList[ind], 'latestValuation', this.formatNum((item.latestShareholdingRatio / 100) * this.form.overallProjectCompany))
      })
    },
    /** 编辑估值方法 **/
    editMethod(row) {
      this.methodOpen(row.valuationMethods, 'edit')
    },
    /** 删除估值方法 */
    delMethod(index, row) {
      var _this = this
      this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(function() {
        if (_this.isEmpty(row.id)) {
          return _this.form.dealAnalysisValuationMethodList.splice(index, 1)
        } else {
          return deleteAnalysisValuationMethod(row.id)
        }
      }).then(() => {
        _this.form.dealAnalysisValuationMethodList.splice(index, 1)
        if (row.valuationMethods === _this.form.valuationMethods) {
          _this.form.valuationMethods = undefined
          _this.form.overallProjectCompany = 0
          _this.form.dealValuation = 0
          _this.form.valuationChanges = 0
          _this.form.moic = 0
          _this.form.irr = 0
        }
        _this.msgSuccess(_this.$t('删除成功'))
      }).catch(function() {
      })
    },
    /** 格式化金额, 保留精度及小数 **/
    formatNum(num) {
      if (num === null || num === undefined || isNaN(num)) {
        num = 0
      }
      return ruoyiFloat().formatNum(Number(num).toFixed(4))
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.loading = true
          saveDealAnalysisValuation(this.form).then(response => {
            // 缓存最新融资法填写的内容
            if (this.backFinancingLawData !== undefined) {
              this.backFinancingLawData.dealId = this.form.dealId
              saveMethodFinancingCache(this.backFinancingLawData)
            }
            if (response.code === 200) {
              this.msgSuccess(this.$t('保存成功'))
              this.generReport(response.data.id)
              this.closeForm()
            } else {
              this.msgError(response.msg)
            }
            this.loading = false
          }).catch(() => {
            this.loading = false
          })
        } else {
          this.locationError(document)
        }
      })
    },
    /** 生成报告 **/
    generReport(id) {
      saveDealAnalysisValuationReport({ valuationId: id, dealId: this.form.dealId })
    }
  }
}
</script>
<style scoped lang="scss">
/deep/ .el-radio__label {
  display: none !important;
}
/deep/input.colorRed /deep/.el-input /deep/.el-input__inner {
  color: red !important;
}
</style>
